using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.IO;

namespace Spinning.Spinning.Unitity.Storage
{
   public class XmlStorage<T>
    {
        string fileName;
        Type t;

        public XmlStorage(string fileName)
        {
            this.fileName = fileName;
            t = typeof(T);
        }

        public void Save(T o)
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream stream = storage.CreateFile(fileName);
            XmlSerializer xml = new XmlSerializer(o.GetType());
            xml.Serialize(stream, o);

            stream.Close();
            stream.Dispose();
        }

        public bool FileExists() {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            return storage.FileExists(fileName);
        }

        public T Load()
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            T obj=default(T);

            if (storage.FileExists(fileName))
            {
                IsolatedStorageFileStream stream =
                storage.OpenFile(fileName, FileMode.Open);
                XmlSerializer xml = new XmlSerializer(t);

                obj = (T)xml.Deserialize(stream);

                stream.Close();
                stream.Dispose();
            }

            return obj;
        }

    }
}
